<template>
  <el-drawer
    :title="type?'批量修改收费配置': editInfo.id ? '修改收费配置':'新增收费配置'"
    :visible="show"
    size="670px"
    :append-to-body="true"
    @close="close"
  >
    <el-form
      ref="form"
      :model="ruleForm"
      label-position="top"
      :rules="rules"
      label-width="80px"
      class="form"
    >
      <!-- 批量修改收费没有短剧 -->
      <el-form-item
        v-if="!type"
        label="短剧"
        prop="playlet_id"
      >
        <el-select
          v-model="ruleForm.playlet_id"
          clearable
          placeholder="请选择短剧"
          style="width:100%;"
          filterable
          @change="charpterChange"
        >
          <el-option
            v-for="item in selectList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="定价"
        prop="pay_coin"
      >
        <div class="rowFlex columnCenter">
          <el-input
            v-model="ruleForm.pay_coin"
            placeholder="请输入定价"
            style="width:250px;"
            @input="ruleForm.pay_coin = ruleForm.pay_coin.replace(/\D|/g,'') "
          ></el-input>
          <span style="margin-left:10px;">虚拟币/集</span>
        </div>
      </el-form-item>
      <el-form-item
        label="开始付费剧集"
        prop="start_pay_chapter"
        class="chapter"
      >
        <el-select
          v-model="ruleForm.start_pay_chapter"
          clearable
          placeholder="请选择短剧"
          style="width:100%;"
          @change="chapterChange"
        >
          <el-option
            v-for="item in chapterList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <div
        v-if="ruleForm.step && ruleForm.step.length > 0"
        class="step"
      >
        <div class="messagesActive">
          <div class="icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="text">
            设置阶梯价的集数将优先用阶梯价定价，未设置阶梯价集数统一用初始定价
          </div>
        </div>
        <div class="step_list">
          <el-row class="elrow">
            <div
              v-for="(item, index) in ruleForm.step"
              :key="index"
              style="display: flex; align-items: center;"
            >
              <span>
                集数
              </span>
              <el-col :span="6">
                <el-form-item
                  :prop="'step.' + index + '.start_chapter'"
                  :rules="[{ required: true, validator:validatestart_chapter, trigger: 'blur' },
                           { required: true, message: '请输入', trigger: 'blur'},
                           { required: true, validator:(rule, value, callback) => {
                             if(index == 0) {
                               callback()
                             }else {
                               if (ruleForm.step[index-1].end_chapter * 1 >= value * 1) {
                                 callback(onerr('本条起始集数需>上条结束集数'))
                               }else {
                                 callback()
                               }
                             }
                           } , trigger: 'blur' },
                           {
                             required: true, validator:(rule, value, callback) => {
                               if (chapterList.length*1 < value * 1) {
                                 callback(onerr('起始集数≤本剧最大集数'))
                               }else {
                                 callback()
                               }
                             } , trigger: 'blur'
                           }]"
                >
                  <el-input
                    v-model="item.start_chapter"
                    placeholder="起始集数"
                    style="width: 150px;"
                    type="number"
                    @input="item.start_chapter = item.start_chapter.replace(/\D|^0/g,'') "
                  > </el-input>

                </el-form-item>
              </el-col>
              <span>-</span>
              <el-col :span="6">
                <el-form-item
                  :prop="'step.' + index + '.end_chapter'"
                  :rules="[{ required: true, message: '请输入', trigger: 'blur'},
                           { required: true, validator:(rule, value, callback) => {
                             if ( item.start_chapter * 1 > value * 1) {
                               callback(onerr('结束集数需≥起始集数'))
                             }else {
                               callback()
                             }
                           } , trigger: 'blur' },
                           {
                             required: true, validator:(rule, value, callback) => {
                               if (chapterList.length*1 < value * 1) {
                                 callback(onerr('结束集数需≤本剧最大集数'))
                               }else {
                                 callback()
                               }
                             } , trigger: 'blur'
                           }]"
                >
                  <el-input
                    v-model="item.end_chapter"
                    placeholder="结束集数"
                    style="width: 150px;"
                    type="number"
                    @input="item.end_chapter = item.end_chapter.replace(/\D|^0/g,'') "
                  > </el-input>
                </el-form-item>
              </el-col>
              <span>阶梯价</span>
              <el-col :span="6">
                <el-form-item
                  :prop="'step.' + index + '.step_coin'"
                  :rules="[
                    { required: true, message: '请输入', trigger: 'blur'},
                    { required: true, validator:validateCoin, trigger: 'blur',playlet_id:ruleForm.playlet_id}
                  ]"
                >
                  <el-input
                    v-model="item.step_coin"
                    placeholder="虚拟币/集"
                    style="width: 150px;"
                    type="number"
                    @input="item.step_coin = item.step_coin.replace(/\D|^0/g,'') "
                  > </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%;"
              >
                <div style="height: 100%; display: flex; align-items: center;">
                  <i
                    style="margin-left: 10px; font-size: 20px; color: #06c021; cursor: pointer"
                    class="el-icon-remove-outline"
                    @click="onDelStep(index)"
                  ></i>
                </div>
              </el-col>
            </div>
          </el-row>
        </div>
        <el-button
          class="addStep"
          @click="onAddStep"
        > <i
            class="el-icon-plus"
            style="font-weight: bold;"
          ></i><span>添加阶梯价</span></el-button>
      </div>
      <el-button
        v-else
        style="margin-bottom: 18px;"
        @click="onAddStep"
      > <i
          class="el-icon-plus"
          style="font-weight: bold;"
        ></i><span>添加阶梯价</span></el-button>
      <Consumption
        v-if="templatePreviewData.first_ist && (ruleForm.pay_coin|| ruleForm.step) && ruleForm.start_pay_chapter && chapterList.length"
        :rule="ruleForm.step"
        :template="templatePreviewData.first_ist"
        :initial="ruleForm.pay_coin *1"
        :start="ruleForm.start_pay_chapter*1"
        :total="chapterList.length*1"
      >
      </consumption>
    </el-form>
    <span class="dialog-footer rowFlex">
      <el-button
        class="btn"
        @click="close"
      >取 消</el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="submit"
      >确 定</el-button>
    </span>
  </el-drawer>
</template>

<script type="text/javascript">
import Consumption from '@/components/Consumption'
import { mapState, mapMutations, mapActions } from 'vuex'
import { channelPlayletSave, templatePreview } from '@/api/channel'
import { commonData } from '@/api/common'
import { validateCoin, validateStart, reqeustPayInfo } from '@/utils/index'
import { batchChannelPlayletSave } from '@/api/channel'

export default {
  computed: {
    ...mapState('common', ['commonDataList'])
  },
  components: { Consumption },
  // type Batch 渠道的批量修改收费配置
  props: ['show', 'rowInfo', 'editInfo', 'type', 'channelId', 'playletIds'],
  data() {
    var validatestart_chapter = (rule, value, callback) => {
      if (value < this.ruleForm.start_pay_chapter) {
        callback(new Error('起始收费集数需≥开始付费剧集'))
      } else {
        callback()
      }
    }
    return {
      validatestart_chapter: validatestart_chapter,
      validateCoin: validateCoin,
      ruleForm: {
        mini_app_id: '',
        channel_id: '',
        playlet_id: '',
        pay_coin: '',
        id: '',
        playlet_name: '',
        start_pay_chapter: '',
        step: []
      },
      selectList: [],
      loading: false,
      chapterList: [],
      templatePreviewData: {},
      rules: {
        playlet_id: [{ required: true, message: '请选择短剧', trigger: 'change' }],
        start_pay_chapter: [
          { required: true, message: '请选择开始付费剧集', trigger: 'change' },
          { required: true, validator: validateStart, trigger: 'change' }
        ],
        pay_coin: [
          { required: true, message: '请输入定价', trigger: 'blur' },
          { required: true, validator: validateCoin, trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    this.selectList = await this.requestCommonData({ type: 'playlet', mini_app_id: window.localStorage.getItem('mini_app_id') })
  },
  mounted() {
    reqeustPayInfo()
    console.log(this.playletIds, '>>>>>>>>>>>>>>>>>>>>')
    this.init()
  },
  methods: {
    onerr(str) {
      return new Error(str)
    },
    chapterChange() {
      this.$refs.form.validate('rules')
    },
    async onGettemplatePreview() {
      const res = await templatePreview({
        template_id: this.rowInfo.template_id
      })
      if (res.status_code === 1) {
        this.templatePreviewData = res.data.data
      }
    },
    onDelStep(index) {
      this.ruleForm.step.splice(index, 1)
    },
    onAddStep() {
      if (!this.ruleForm.step) {
        this.ruleForm.step = []
      }
      this.ruleForm.step.push({
        start_chapter: '',
        end_chapter: '',
        step_coin: ''
      })
    },
    ...mapActions('common', ['requestCommonData']),
    init() {
      console.log(this.rowInfo, 'rowInfo')
      console.log(this.editInfo, 'editInfo')
      this.rowInfo.template_id ? this.onGettemplatePreview() : ''
      // this.requestCommonData({ type: 'playlet' })
      if (this.editInfo.id) {
        const editInfo = JSON.parse(JSON.stringify(this.editInfo))
        this.ruleForm.playlet_id = Number(editInfo.playlet_id)
        this.ruleForm.pay_coin = editInfo.pay_coin
        this.ruleForm.playlet_title = Number(editInfo.playlet_title)
        this.ruleForm.start_pay_chapter = Number(editInfo.start_pay_chapter)
        this.ruleForm.id = editInfo.id
        this.ruleForm.playlet_name = editInfo.playlet_name
        editInfo.step == '' ? (editInfo.step = []) : ''
        this.ruleForm.step = editInfo.step
        this.reqeustChapter(this.ruleForm.playlet_id)
        this.rules.pay_coin = [
          { required: true, message: '请输入定价', trigger: 'blur' },
          { required: true, validator: validateCoin, trigger: 'blur', playlet_id: this.ruleForm.playlet_id }
        ]
      } else {
      }
      if (this.type) {
        this.reqeustChapter()
      }
    },
    close() {
      this.$emit('update:show', false)
    },
    reqeustChapter(value) {
      // type: batch 批量修改付费设置的时候 chapterList 为1-50
      if (this.type) {
        const list = []
        for (let index = 1; index < 51; index++) {
          list.push({ label: `第${index}集`, value: index })
        }
        this.chapterList = list
        this.rules.pay_coin = [
          { required: true, message: '请输入定价', trigger: 'blur' },
          { required: true, validator: validateCoin, trigger: 'blur', playlet_id: this.playletIds, visibelType: this.type }
        ]
      } else {
        commonData({ type: 'playletChapter', value: value }).then((res) => {
          if (res.status_code === 1) {
            this.chapterList = res.data.data
          }
        })
      }
    },
    charpterChange(value) {
      const name = this.commonDataList.playlet.find((item) => item.value === value)
      this.ruleForm.playlet_name = name.label
      this.ruleForm.start_pay_chapter = ''
      this.rules.pay_coin = [
        { required: true, message: '请输入定价', trigger: 'blur' },
        { required: true, validator: validateCoin, trigger: 'blur', playlet_id: this.ruleForm.playlet_id }
      ]
      this.reqeustChapter(value)
    },
    switchChannelPlayletSave(data) {
      return new Promise((resolve, reject) => {
        if (this.type) {
          batchChannelPlayletSave(data).then(
            (res) => {
              resolve(res)
            },
            (err) => {
              reject(err)
            }
          )
        } else {
          channelPlayletSave(data).then(
            (res) => {
              resolve(res)
            },
            (err) => {
              reject(err)
            }
          )
        }
      })
    },
    // 针对单个渠道配置
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const { playlet_id, pay_coin, start_pay_chapter, playlet_name, step = [] } = this.ruleForm
          const data = {
            mini_app_id: this.rowInfo.mini_app_id,
            channel_id: this.rowInfo.id,
            playlet_id,
            pay_coin,
            playlet_name,
            start_pay_chapter,
            step
          }
          this.ruleForm.id ? (data.id = this.ruleForm.id) : ''
          this.type ? (data.channel_id = this.channelId) : ''
          this.switchChannelPlayletSave(data).then(
            (res) => {
              this.loading = false
              if (res.status_code === 1) {
                this.$message.success(res.msg)
                this.close()
                this.$emit('result')
                setTimeout(() => {
                  this.$emit('result')
                  this.ruleForm = {
                    mini_app_id: '',
                    channel_id: '',
                    playlet_id: '',
                    pay_coin: '',
                    id: '',
                    start_pay_chapter: ''
                  }
                }, 500)
              }
            },
            (err) => {
              this.loading = false
            }
          )
        } else {
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form {
  width: 100%;
  padding: 20px;
  padding-bottom: 90px;
  ::v-deep .el-form-item__label {
    font-weight: 600;
  }

  .step {
    background: #f7f8fa;
    border-radius: 3px;
    padding: 16px;
    margin-bottom: 18px;
    ::v-deep.el-form-item__error {
      white-space: nowrap;
    }
    .elrow {
      ::v-deep.el-col-10 {
        width: 100px;
        margin: 0 8px;
      }
      span {
        flex-shrink: 0;
        margin: 0 5px;
      }
      ::v-deep.el-form-item.is-required.el-form-item--small {
        margin: 10px 0;
      }
    }
  }
}
.chapter {
  ::v-deep .el-form-item__label {
    line-height: 20px;
  }
}
.messagesActive {
  margin: 0;
}
.addStep {
  margin-top: 10px;
}
</style>
